<template>
  <div class="">
    <mu-container v-loading="loading" style="max-width: 100%!important;">
      <mu-row class="padt10">
        <mu-paper :z-depth="3" style="width: 100%" class="round5 ">
          <mu-flex align-items="center">
            <mu-flex>
              <mu-button icon color="primary">
                <mu-icon value="extension"></mu-icon>
              </mu-button>
            </mu-flex>
            <mu-flex fill><h5>{{title}}</h5></mu-flex>
            <mu-flex>
              <div class="padr10" slot="">
                <mu-button small flat color="error" @click="deleteAll()">
                  <mu-icon left value="delete"></mu-icon>
                  删除
                </mu-button>
                <mu-button small round color="success" @click="$goto('/admin/edit/auto',{en:en})">
                  <mu-icon left value="add"></mu-icon>
                  新增
                </mu-button>
              </div>
            </mu-flex>
          </mu-flex>
        </mu-paper>
      </mu-row>

      <mu-row class="padt10">
        <mu-paper style="width: 100%" :z-depth="3">
          <mu-flex align-items="center" class="padt2 padb2">
            <mu-flex>
              <mu-sub-header>模糊查询：</mu-sub-header>
            </mu-flex>
            <mu-flex fill>
              <mu-text-field :action-click="getList" class="padl10" action-icon="search" solo v-model="search_" placeholder="请输入关键词"></mu-text-field>
            </mu-flex>
          </mu-flex>
          <div v-if="showSearch">
            <mu-row align-items="center">
              <mu-col v-for="(item,index) in searchBox" :key="index" :span="item.width">
                <template v-if="item.type === 'text'">
                  <mu-text-field icon="keyboard" solo v-model="where_[item.expression][item.name]" :placeholder="item.helpText"></mu-text-field>
                </template>
                <template v-if="item.type === 'date'">
                  <mu-date-input solo icon="access_time" v-model="where_[item.expression][item.name]" :placeholder="item.helpText" type="dateTime" actions full-width landscape></mu-date-input>
                </template>
                <template v-if="item.type === 'select'">
                  <mu-select icon="format_indent_increase" class="" :placeholder="item.helpText" filterable v-model="where_[item.expression][item.name]" full-width>
                    <mu-option v-for="(choice,idx) in item.choices" :key="idx" :label="choice.value" :value="choice.id"></mu-option>
                  </mu-select>
                </template>
              </mu-col>
              <mu-col v-if="excel">
                  <mu-button flat small round color="orange" @click="excelOut()">
                    <mu-icon left value="cloud_download"></mu-icon>
                    <span class="padr10">导出Excel</span>
                  </mu-button>
              </mu-col>
              <mu-col>
                  <mu-button flat small round color="primary" @click="getList()">
                    <mu-icon left value="search"></mu-icon>
                    <span class="padr10">查询</span>
                  </mu-button>
              </mu-col>
            </mu-row>
          </div>
        </mu-paper>
      </mu-row>
      <mu-row class="padt10">
        <mu-paper style="width: 100%" :z-depth="3">
          <div v-if="showAction">
            <mu-row align-items="center">
              <mu-col v-for="(item,index) in actionBox" :key="index" :span="item.width">
                <template v-if="item.type === 'text'">
                  <mu-text-field icon="keyboard" solo v-model="action_[item.name]" :placeholder="item.helpText"></mu-text-field>
                </template>
                <template v-if="item.type === 'date'">
                  <mu-date-input solo icon="access_time" v-model="action_[item.name]" :placeholder="item.helpText" type="dateTime" actions full-width landscape></mu-date-input>
                </template>
                <template v-if="item.type === 'select'">
                  <mu-select icon="format_indent_increase" class="" :placeholder="item.helpText" filterable v-model="action_[item.name]" full-width>
                    <mu-option v-for="(choice,idx) in item.choices" :key="idx" :label="choice.value" :value="choice.id"></mu-option>
                  </mu-select>
                </template>
              </mu-col>
              <mu-col span="3">
                <mu-flex justify-content="center" class="pad5">
                  <mu-button small round color="error" @click="action()">
                    <mu-icon left value="search"></mu-icon>
                    <span class="padr10">批量设置</span>
                  </mu-button>
                </mu-flex>
              </mu-col>
            </mu-row>
          </div>
        </mu-paper>
      </mu-row>
      <mu-row class="padt10">
        <mu-paper style="width: 100%" :z-depth="3">
          <mu-data-table class="data-table"  height="500" selectable select-all :selects.sync="selects" checkbox :columns="headers" :data="list" :fit="true">
            <template slot-scope="scope">
              <!--            <td align="center" v-for="(item,index) in header" :key="index">{{scope.row[item]}}</td>-->
              <td align="center" v-for="(item,index) in header" :key="index">
                <div v-if="$com.isbool(config) &&$com.isbool(config[item]) && config[item].listType === 'pic'">
                  <img @click="()=>{picView = $api.getUrl() + scope.row[item];openDialog = true}" style="max-width: 200px; max-height: 150px;" :src="$api.getUrl() + scope.row[item]" alt="">
                </div>
                <div v-else>{{guessItem(scope.row,item)}}</div>
              </td>
              <td align="center">
                <mu-row align-items="center" justify-content="center">
                  <mu-flex>
                    <mu-button flat small color="primary" @click="$goto('/admin/machine/edit/edit',{id:scope.row.id,en:en})">
<!--                      <mu-icon left value="edit"></mu-icon>-->
                      编辑
                    </mu-button>
                  </mu-flex>
                  <mu-flex>
                    <mu-menu placement="bottom-end" open-on-hover>
                      <mu-button icon small>
                        <mu-icon value="more_vert"></mu-icon>
                      </mu-button>
                      <mu-list slot="content">
                        <mu-list-item button dense @click="deleteAll(scope.row.id)">
                          <span class="fs8">删除</span>
                        </mu-list-item>
                        <mu-list-item button dense @click="copy(scope.row.id)">
                          <span class="fs8">复制</span>
                        </mu-list-item>
                      </mu-list>
                    </mu-menu>
                  </mu-flex>
                </mu-row>
              </td>
            </template>
          </mu-data-table>
        </mu-paper>
      </mu-row>
      <mu-row class="padt10 padb20" v-show="page.limit < page.total">
        <mu-flex justify-content="center">
          <mu-pagination @change="getList" :page-size="page.limit" raised :total="page.total * 1" :current.sync="page.page"></mu-pagination>
        </mu-flex>
      </mu-row>
      <!--    隐藏项目-->
      <mu-dialog title="预览" :open.sync="openDialog">
        <img :src="picView" alt="">
        <mu-button slot="actions" flat color="primary" @click="openDialog = false">关闭</mu-button>
      </mu-dialog>
    </mu-container>
  </div>
</template>
<script>
import com from '@/assets/js/com'
import api from '@/assets/js/api'

export default {
  name: 'auto',
  data () {
    return {
      onload: true,
      entityName: '',
      title: '列表',
      loading: true,
      baseUrl: api.getUrl(),
      // 实体信息
      en: '',
      config: [],
      // 数据筛选相关
      search_: '',
      where_: undefined,
      order_: {id: 'desc'},
      options_: {},
      excel_: false,
      action_: undefined,
      searchBox: [],
      showSearch: false,
      actionBox: [],
      showAction: false,
      excel: false,
      // 列表相关数据
      selects: [],
      header: [],
      headers: [],
      list: [],
      page: {total: 0, limit: 10, page: 1},
      openDialog: false,
      picView: ''
    }
  },
  methods: {
    getList (page) {
      let _this = this
      _this.loading = true
      // 处理分页信息
      if (page !== undefined) {
        _this.page.page = page
      }
      // 处理条件筛选

      let url = '/admin/' + this.entityName + '/list'
      api.post(url, {
        page: _this.page.page,
        _where: _this.where_,
        _order: _this.order_,
        _search: _this.search_
      }, function (res) {
        _this.loading = false
        // 实体名称
        _this.title = res.d.title
        // 实体名称
        _this.en = res.d.en
        // 分页数据
        _this.page = res.d.page
        // 处理表头信息-默认处理也可以自己配置
        _this.header = res.d.header
        let config = res.d.config
        _this.config = res.d.config
        _this.headers = []
        if (_this.headers.length === 0) {
          _this.header.map(function (name) {
            let array = name.split('.')
            name = array[0]
            _this.headers.push({title: config[name].cnName, name: name, width: config[name].width})
          })
          _this.headers.push({title: '编辑', align: 'center', name: 'edit', width: 180})
        }
        // 列表数据
        // 对象处理
        res.d.lists.map(function (row) {
          for (let i in row) {
            // 检测对象类型
            if (typeof row[i] === 'object' && row[i] != null) {
              // console.log(row[i])
              // console.log(row)
              // console.log(i)
              // if (com.isTrue(row[i][0])) {
              //   row[i] = '[Array]'
              // } else {
              //   row[i] = row[i].name === undefined ? (row[i].title === undefined ? row[i] : row[i].title) : row[i].name
              // }
            }
            // 检测时间类型
            var reg = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d(\+08:00)$/
            var regExp = new RegExp(reg)
            if (regExp.test(row[i])) {
              // alert("时间格式不正确,正确格式为: 2014-01-01 12:00:00 ");
              row[i] = com.str2time(row[i])
            }
            if (row[i] === true || row[i] === false) {
              row[i] = row[i] ? '是' : '否'
            }
          }
        })
        _this.list = res.d.lists

        // 设置筛选数据
        if (res.d.searchBox === undefined) {
          _this.showSearch = false
        } else {
          if (_this.onload === true) {
            _this.showSearch = res.d.searchBox.show
            _this.excel = res.d.searchBox.excel
            if (_this.where_ === undefined) {
              _this.where_ = res.d.searchBox.attr
              _this.searchBox = res.d.searchBox.box
            }
          }
        }

        // 设置操作盒
        if (res.d.actionBox === undefined) {
          _this.showAction = false
        } else {
          if (_this.onload === true) {
            _this.showAction = res.d.actionBox.show
            _this.action_ = res.d.actionBox.items
            _this.actionBox = res.d.actionBox.box
          }
        }
        // if (res.d.actionBox === undefined || _this.onload === false) {
        //   _this.showAction = false
        // } else {
        //   _this.showAction = res.d.actionBox.show
        //   console.log(res.d.actionBox.box)
        //   _this.action_ = res.d.actionBox.items
        //   _this.actionBox = res.d.actionBox.box
        // }
        _this.onload = false
      })
    },
    excelOut () {
      let _this = this
      _this.loading = true
      api.download('/admin/' + this.entityName + '/excel', {
        _where: _this.where_,
        _order: _this.order_,
        _search: _this.search_
      }, function (res) {
        _this.loading = false
      })
    },
    deleteAll (cur) {
      let _this = this
      this.$confirm('确定要删除？', '提示', {
        type: 'warning'
      }).then(({result}) => {
        if (result) {
          // 点击了确定按钮，执行删除动作
          let ids = []
          if (cur !== undefined) {
            ids = [cur]
          } else {
            _this.selects.map(function (index) {
              ids.push(_this.list[index].id)
            })
          }
          // 执行删除动作
          let url = '/admin/' + this.entityName + '/delete'
          api.post(url, {ids}, function (res) {
            if (res.s * 1 === 1) {
              _this.$toast.message(res.i)
              // 重载数据
              _this.getList()
            }
          })
        }
      })
    },
    action (cur) {
      let _this = this
      // _this.loading = true
      this.$confirm('正在执行批量修改，请确认操作！', '提示', {
        type: 'warning'
      }).then(({result}) => {
        if (result) {
          // 点击了确定按钮，执行删除动作
          let ids = []
          if (cur !== undefined) {
            ids = [cur]
          } else {
            _this.selects.map(function (index) {
              ids.push(_this.list[index].id)
            })
          }
          // 执行删除动作

          api.post('/admin/' + this.entityName + '/action', {
            ids: ids,
            _action: _this.action_
          }, function (res) {
            // _this.loading = false
            _this.getList()
          })
        }
      })
    },
    copy (id) {
      let _this = this
      let url = '/admin/' + this.entityName + '/copy'
      api.get(url, {id}, function (res) {
        if (res.s * 1 === 1) {
          _this.getList()
        }
      })
    },
    guessItem (row, itemName) {
      // scope.row[item]
      if (com.isbool(itemName)) {
        itemName = itemName.split('.')
        if (typeof itemName === 'string') {
          return row[itemName]
        } else {
          let parent = row
          let value = ''
          for (let i in itemName) {
            // console.log(parent)
            if (!com.isbool(parent[itemName[i]])) {
              return ''
            }
            value = parent[itemName[i]]
            parent = parent[itemName[i]]
          }
          return value
        }
      } else {
        return ''
      }
    }
  },
  created () {
    this.entityName = this.$route.query.en
  },
  mounted () {
    this.getList()
  },
  watch: {
    '$route' (to, from) {
      this.entityName = to.query.en
      this.where_ = undefined
      this.action_ = undefined
      this.showSearch = false
      this.showAction = false
      // this.onload = true
      // this.getList()
    },
    entityName () {
      console.log(this.entityName)
      this.onload = true
      this.getList()
    }
  }
}
</script>

<style scoped>

</style>
